<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        margin: 0px;
        left: 0px;
      }
      .box2 {
        width: 100px;
        height: 100px;
        background-color: yellow;
        position: absolute;
        margin: 0px;
        left: 200px;
      }
    </style>
  </head>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      var box1Ele = document.querySelector(".box1");
      var box2Ele = document.querySelector(".box2");
      box1Ele.onmousedown = function (event) {
        var e = event || window.event;
        var x = e.clientX - box1Ele.offsetLeft;
        var y = e.clientY - box1Ele.offsetTop;
        box1Ele.onmousemove = function (event) {
          var e = event || window.event;
          var xx = e.clientX;
          var yy = e.clientY;
          box1Ele.style.left = xx - x + "px";
          box1Ele.style.top = yy - y + "px";
          //   if (
          //     Math.abs(box2Ele.offsetLeft - box1Ele.offsetLeft) <
          //       box1Ele.offsetWidth &&
          //     Math.abs(box2Ele.offsetTop - box1Ele.offsetTop) <
          //       box1Ele.offsetHeight
          //   ) {
          //     console.log("碰撞了");
          //   }
          var AminX = box1Ele.offsetLeft;
          var AmaxX = box1Ele.offsetLeft + box1Ele.offsetWidth;
          var BminX = box2Ele.offsetLeft;
          var BmaxX = box2Ele.offsetLeft + box2Ele.offsetWidth;
          var AminY = box1Ele.offsetTop;
          var AmaxY = box1Ele.offsetTop + box1Ele.offsetHeight;
          var BminY = box2Ele.offsetTop;
          var BmaxY = box2Ele.offsetTop + box2Ele.offsetHeight;

          if (
            AmaxX > BminX &&
            AminX < BmaxX &&
            AmaxY > BminY &&
            AminY < BmaxY
          ) {
            console.log("碰撞了");
          }
        };
        document.onmouseup = function () {
          box1Ele.onmousemove = "";
        };
      };
    </script>
  </body>
</html>
